var app = getApp();

Page({
	data: {
		origin: {
			longitude: '',
			latitude: ''
		},
		markers: [],
		polyline: []
	},

	//事件处理函数
	onLoad: function (options) {
		let orderId = options.id || 1;
		this.getOrderPath(orderId);
	},

	onShow: function(){

	},

	getOrderPath(orderId) {
		let $this = this;
		app.battery.common('battery/path', {
			ticket: app.data.token,
			orderId: orderId
		}).then(function (d) {
			let startMarker = {},
				endMarker = {},
				markers = [],
				markerList = [],
				longitude = 0,
				latitude = 0;

			if (d.length > 0) {
				startMarker = {
					iconPath: "../../image/icon/mapicon_navi_s.png",
					id: 0,
					latitude: d[0].gsmLat,
					longitude: d[0].gsmLng,
					width: 23,
					height: 33
				};

				markers.push(startMarker);
				markerList.push(startMarker);
			}

			if (d.length > 1) {
				if (d.length > 2) {
					for (let i = 1; i < d.length - 1; i++) {
						markerList.push({
							latitude: d[i].gsmLat,
							longitude: d[i].gsmLng
						})
					}
				}

				endMarker = {
					iconPath: "../../image/icon/mapicon_navi_e.png",
					id: d.length - 1,
					latitude: d[d.length - 1].gsmLat,
					longitude: d[d.length - 1].gsmLng,
					width: 23,
					height: 33
				};

				markers.push(endMarker);
				markerList.push(endMarker);
			}

			markers.forEach(v => {
				longitude += v.longitude;
				latitude += v.latitude;
			});

			$this.setData({
				markers: markers,
				origin: {
					longitude: longitude / markers.length,
					latitude: latitude / markers.length
				}
			});

			if (d.length > 1) {
				$this._getDrivingRoute(markerList);
			}

		}).catch(function (e) {
			console.log(e)
		});
	},

	_getDrivingRoute: function (passList) {
		let that = this;
		let points = [];
		let resList = [];

		for (let k = 0; k < passList.length - 1; k++) {
			resList.push(app.map.getRidingRoute(`${passList[k].longitude}, ${passList[k].latitude}`,
				`${passList[k+1].longitude}, ${passList[k+1].latitude}`))
		}

		Promise.all(resList)
			.then(res => {
				res.forEach(item => {
					if(item.paths && item.paths[0] && item.paths[0].steps){
						let steps = item.paths[0].steps;
						for(let i = 0; i < steps.length; i++){
							let poLen = steps[i].polyline.split(';');
							for(let j = 0; j < poLen.length; j++){
								points.push({
									longitude: parseFloat(poLen[j].split(',')[0]),
									latitude: parseFloat(poLen[j].split(',')[1])
								})
							}
						}
					}
				});

				that.setData({
					polyline: [{
						points: points,
						color: "#0091ff",
						width: 6
					}]
				});

			})
			.catch(err => {
				console.log(err)
			});
	}
});
